//在Flutter中系统已经为我们提供了google material design的刷新效果，
// 我们可以使用RefreshIndicator组件来实现Flutter中的下拉刷新，

//const RefreshIndicator({
//Key key,
//@required this.child,
//this.displacement: 40.0,下拉展示距离
//@required this.onRefresh,刷新回调
//this.color,//刷新进度颜色
//this.backgroundColor,//背景颜色
//this.notificationPredicate: defaultScrollNotificationPredicate,
//})

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_practice/utils/Utils.dart';

class MyRefreshDemo extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return  MyRefreshState();
  }
}

class MyRefreshState extends State<MyRefreshDemo>{

  List<int> items = List.generate(16, (i) => i);

//  在ListView中有一个ScrollController属性，
// 它就是专门来控制ListView滑动事件，
// 在这里我们可以根据ListView的位置来判断是否滑动到了底部来
// 做加载更多的处理。
  ScrollController controller = new ScrollController();

  //下拉刷新
  Future<Null> _handleRefresh() async{
    await Future.delayed(Duration(seconds: 5 ),(){
      print('refresh');
      setState(() {
        items.clear();
        items = List.generate(40,(i)=> i );
        return null;
      });
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller.addListener((){
      if(controller.position.pixels == controller.position.maxScrollExtent){
        print('加载更多');
        _getMoreData();
      }
    });
  }

  Future _getMoreData() async{
    List<int> newEntries = await mokeHttpRequest(items.length, items.length+10);
    setState(() {
      items.addAll(newEntries);
    });
  }

  Future<List<int>> mokeHttpRequest(int from,int to) async{
    return Future.delayed(Duration(seconds: 2,),(){
      return List.generate(to-from, (i) => i+from);
    });
  }



  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(appBar: Utils.getAppBar('刷新'),
     body: RefreshIndicator(child: ListView.builder(itemBuilder: (context,index){
       return ListTile(title: Text('Index$index'),);
     }, itemCount: items.length,controller: controller,),
         onRefresh: _handleRefresh),
    );
  }
}